package cn.dida.core;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.dida.exception.BizzException;
import cn.dida.model.Sysres;
import cn.dida.model.UserSession;
/**
 * 权限检查拦截器
 * @author weiwei
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private Log logger = LogFactory.getLog(getClass());

    /**
     * 权限检查
     * @return boolean true有权限，false无权限
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       
        UserSession userSession = (UserSession) request.getAttribute(Constants.USER_SESSION_KEY);
        //System.out.println("请求url："+request.getRequestURL());
        Sysres Current_Res_Node = (Sysres) request.getAttribute("Current_Res_Node");
        
        if (Current_Res_Node == null) {
            return true;
        }
        if (StringUtils.isEmpty(userSession.getResIds())) {
            handleUnAuthorized(request, response);
            return false;
        }

        List<String> staffResIdList = Arrays.asList(StringUtils.split(userSession.getResIds(), ","));
        if (!staffResIdList.contains(Current_Res_Node.getId().toString())) {
            handleUnAuthorized(request, response);
            return false;
        } else {
            if (!StringUtils.equals(request.getMethod(), Current_Res_Node.getMethod())) {
                handleUnAuthorized(request, response);
                return false;
            }
        }
        return true;
    }

    private void handleUnAuthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
        throw new BizzException(BizzException.error_code_unauthorized, "您没有权限进行此操作");
    }

}